﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Transport.Core.Models.Users;
using Transport.Data.Mapping.Users;
using Transport.Core.Models.ContentManagement;
using Transport.Core.Models.Settings;

namespace Transport.Data
{
    public class TransportContextInitializer : DropCreateDatabaseIfModelChanges<TransportContext>
    {
        /// <summary>
        /// Dummy data
        /// </summary>
        /// <param name="context"></param>
        protected override void Seed(TransportContext context)
        {
            base.Seed(context);
            //Fixed Data
            CreateRoles(context);
            CreateSupperAdminUser(context);
            CreateStaticPages(context);
            CreateMyOffices(context);
            CreateRateTables(context);
            //CreateRegions(context);
            CreateStateProvinces(context);
            //Example Data
            CreateUsers(context);
            CreateCategories(context);
        }

        private void CreateRoles(TransportContext context)
        {
            var roles = new List<Role>
                            {
                                new Role
                                    {
                                        RoleName = "Admin",
                                        Description = "Admin"
                                    },
                                new Role
                                    {
                                        RoleName = "T.Buu Cuc",
                                        Description = "Truong Buu Cuc"
                                    },
                                new Role
                                    {
                                        RoleName = "Khai Thac",
                                        Description = "Khai Thac"
                                    },
                                new Role
                                    {
                                        RoleName = "KT Truong",
                                        Description = "KT Truong"
                                    },
                                new Role
                                    {
                                        RoleName = "KT Vien",
                                        Description = "KT Vien"
                                    },
                                new Role
                                    {
                                        RoleName = "NV Giao Nhan",
                                        Description = "NV Giao Nhan"
                                    }
                            };

            roles.ForEach(c => context.Roles.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateSupperAdminUser(TransportContext context)
        {
            string passwordSalt = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
            string hashedPassword = PasswordHelper.CreatePasswordHash("123456", passwordSalt);
            //Create user super admin
            var listRoleSuperAdmin = new List<Role> { context.Roles.FirstOrDefault(p => p.RoleName == RoleType.Administrator) };
            context.Users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Le Quang",
                LastName = "Nguyên",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "lequangnguyenqn@gmail.com",
                Username = "brierlytom@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                Roles = listRoleSuperAdmin,
            });
            context.SaveChanges(); //save to database
        }

        private void CreateUsers(TransportContext context)
        {
            string passwordSalt = PasswordHelper.CreatePasswordSalt(PasswordHelper.DEFAULT_SALT_SIZE);
            string hashedPassword = PasswordHelper.CreatePasswordHash("123456", passwordSalt);
            var users = new List<User>();
            //Create list role
            var listRoleAdmin = new List<Role>();
            listRoleAdmin.Add(context.Roles.FirstOrDefault(p => p.RoleName == RoleType.KhaiThac));
            //Create users
            users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Trưởng",
                LastName = "Bưu Cục",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "TBuuCuc" + "@gmail.com",
                Username = "TBuuCuc" + "@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                MyOfficeId = 1,
                Roles = new List<Role>
                {
                    context.Roles.FirstOrDefault(p => p.RoleName == RoleType.TruongBuuCuc)
                }
            });
            users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Kế Toán",
                LastName = "Trưởng",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "KTTruong"  + "@gmail.com",
                Username = "KTTruong" + "@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                MyOfficeId = 1,
                Roles = new List<Role>
                {
                    context.Roles.FirstOrDefault(p => p.RoleName == RoleType.KTTruong)
                }
            });
            users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Kế Toán",
                LastName = "Viên",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "KTVien"  + "@gmail.com",
                Username = "KTVien" + "@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                MyOfficeId = 1,
                Roles = new List<Role>
                {
                    context.Roles.FirstOrDefault(p => p.RoleName == RoleType.KTVien)
                }
            });
            users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Khai",
                LastName = "Thác",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "KhaiThac"  + "@gmail.com",
                Username = "KhaiThac" + "@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                MyOfficeId = 1,
                Roles = new List<Role>
                {
                    context.Roles.FirstOrDefault(p => p.RoleName == RoleType.KhaiThac)
                }
            });
            users.Add(new User
            {
                Address1 = "12 Road Name",
                Address2 = "",
                CompanyName = "Company Name",
                FirstName = "Giao",
                LastName = "Nhận",
                ContactNumber = "01534 123445",
                CountryRegion = "US",
                EmailAddress = "NVGiaoNhan"  + "@gmail.com",
                Username = "NVGiaoNhan" + "@gmail.com",
                PostCodeZip = "HD7 2DS",
                TownCity = "Huddersfield",
                Password = hashedPassword,
                PasswordSalt = passwordSalt,
                IsApproved = true,
                IsLockedOut = false,
                IsOnline = false,
                IsDeleted = false,
                CreateDate = DateTime.Now,
                MyOfficeId = 1,
                Roles = new List<Role>
                {
                    context.Roles.FirstOrDefault(p => p.RoleName == RoleType.NVGiaoNhan)
                }
            });
            users.ForEach(c => context.Users.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateCategories(TransportContext context)
        {
            var categories = new List<NewsCategoryItem>
                            {
                                new NewsCategoryItem
                                    {
                                        CategoryName = "Tin tức",
                                        Active = true,
                                        CategoryDescription = "Tin tức",
                                        DisplayOrder = 0,
                                        IsDeleted = false,
                                        Level = 0,
                                    },
                                new NewsCategoryItem
                                    {
                                        CategoryName = "Tuyển dụng",
                                        Active = true,
                                        CategoryDescription = "Tuyển dụng",
                                        DisplayOrder = 0,
                                        IsDeleted = false,
                                        Level = 0,
                                    },
                            };

            categories.ForEach(c => context.NewsCategoryItems.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateStaticPages(TransportContext context)
        {
            var pages = new List<StaticPage>
                            {
                                new StaticPage
                                    {
                                        Content = "Nhập nội dung vào đây",
                                        Description = "Trang giới thiệu",
                                        IsDeleted = false,
                                        Type = (int)EnumStaticPages.About,
                                    },
                                new StaticPage
                                    {
                                        Content = "Nhập nội dung vào đây",
                                        Description = "Trang liên hệ",
                                        IsDeleted = false,
                                        Type = (int)EnumStaticPages.Contact,
                                    },
                            };

            pages.ForEach(c => context.StaticPages.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateStateProvinces(TransportContext context)
        {
            string dataPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
            using (var reader = new System.IO.StreamReader(dataPath + "\\StateProvinces.txt"))
            {
                do
                {
                    string line = reader.ReadLine();
                    if (string.IsNullOrEmpty(line) == false)
                    {
                        string[] data = line.Split(',');
                        var stateProvince = new StateProvince()
                        {
                            IsDeleted = false,
                            StateProvinceName = data[0].Trim(),
                            StateProvinceCode = data[1].Trim(),
                            MyOfficeId = int.Parse(data[2].Trim())
                        };
                        context.StateProvinces.Add(stateProvince);
                    }
                    else
                    {
                        break;
                    }
                }
                while (true);
            }

            context.SaveChanges(); //save to database
        }

        private void CreateRateTables(TransportContext context)
        {
            var pages = new List<RatesTable>
                            {
                                new RatesTable()
                                {
                                    Description = "Đến 50",
                                    IsExtraColumn = false,
                                    MaxWeight = 50,
                                    MinWeight = 0,
                                    PriceColumnA = 8000,
                                    PriceColumnB = 12500,
                                    PriceColumnC = 12000,
                                    PriceColumnD = 12500,
                                    PriceColumnE = 10500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 50 => 100",
                                    IsExtraColumn = false,
                                    MaxWeight = 100,
                                    MinWeight = 50,
                                    PriceColumnA = 10200,
                                    PriceColumnB = 15000,
                                    PriceColumnC = 15500,
                                    PriceColumnD = 17000,
                                    PriceColumnE = 12500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 100 => 250",
                                    IsExtraColumn = false,
                                    MaxWeight = 250,
                                    MinWeight = 100,
                                    PriceColumnA = 12500,
                                    PriceColumnB = 17000,
                                    PriceColumnC = 20000,
                                    PriceColumnD = 24000,
                                    PriceColumnE = 16000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 250 => 500",
                                    IsExtraColumn = false,
                                    MaxWeight = 500,
                                    MinWeight = 250,
                                    PriceColumnA = 15000,
                                    PriceColumnB = 23000,
                                    PriceColumnC = 27500,
                                    PriceColumnD = 31500,
                                    PriceColumnE = 30000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 500 => 1000",
                                    IsExtraColumn = false,
                                    MaxWeight = 50,
                                    MinWeight = 0,
                                    PriceColumnA = 17000,
                                    PriceColumnB = 32000,
                                    PriceColumnC = 38500,
                                    PriceColumnD = 45500,
                                    PriceColumnE = 41500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1000 => 1500",
                                    IsExtraColumn = false,
                                    MaxWeight = 1500,
                                    MinWeight = 1000,
                                    PriceColumnA = 22000,
                                    PriceColumnB = 41500,
                                    PriceColumnC = 47000,
                                    PriceColumnD = 58000,
                                    PriceColumnE = 53000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1500 => 2000",
                                    IsExtraColumn = false,
                                    MaxWeight = 2000,
                                    MinWeight = 1500,
                                    PriceColumnA = 26500,
                                    PriceColumnB = 49500,
                                    PriceColumnC = 56000,
                                    PriceColumnD = 69500,
                                    PriceColumnE = 63000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },
                                new RatesTable()
                                {
                                    Description = "500 gr tiếp theo",
                                    IsExtraColumn = true,
                                    MaxWeight = 0,
                                    MinWeight = 0,
                                    PriceColumnA = 2800,
                                    PriceColumnB = 5000,
                                    PriceColumnC = 6100,
                                    PriceColumnD = 9000,
                                    PriceColumnE = 8000,
                                    WeightOver = 500,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 1
                                },

                            };
            var pages2 = new List<RatesTable>
                            {
                                new RatesTable()
                                {
                                    Description = "Đến 50",
                                    IsExtraColumn = false,
                                    MaxWeight = 50,
                                    MinWeight = 0,
                                    PriceColumnA = 8000,
                                    PriceColumnB = 12500,
                                    PriceColumnC = 12000,
                                    PriceColumnD = 12500,
                                    PriceColumnE = 10500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 50 => 100",
                                    IsExtraColumn = false,
                                    MaxWeight = 100,
                                    MinWeight = 50,
                                    PriceColumnA = 10200,
                                    PriceColumnB = 15000,
                                    PriceColumnC = 15500,
                                    PriceColumnD = 17000,
                                    PriceColumnE = 12500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 100 => 250",
                                    IsExtraColumn = false,
                                    MaxWeight = 250,
                                    MinWeight = 100,
                                    PriceColumnA = 12500,
                                    PriceColumnB = 17000,
                                    PriceColumnC = 20000,
                                    PriceColumnD = 24000,
                                    PriceColumnE = 16000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 250 => 500",
                                    IsExtraColumn = false,
                                    MaxWeight = 500,
                                    MinWeight = 250,
                                    PriceColumnA = 15000,
                                    PriceColumnB = 23000,
                                    PriceColumnC = 27500,
                                    PriceColumnD = 31500,
                                    PriceColumnE = 30000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 500 => 1000",
                                    IsExtraColumn = false,
                                    MaxWeight = 50,
                                    MinWeight = 0,
                                    PriceColumnA = 17000,
                                    PriceColumnB = 32000,
                                    PriceColumnC = 38500,
                                    PriceColumnD = 45500,
                                    PriceColumnE = 41500,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1000 => 1500",
                                    IsExtraColumn = false,
                                    MaxWeight = 1500,
                                    MinWeight = 1000,
                                    PriceColumnA = 22000,
                                    PriceColumnB = 41500,
                                    PriceColumnC = 47000,
                                    PriceColumnD = 58000,
                                    PriceColumnE = 53000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "Trên 1500 => 2000",
                                    IsExtraColumn = false,
                                    MaxWeight = 2000,
                                    MinWeight = 1500,
                                    PriceColumnA = 26500,
                                    PriceColumnB = 49500,
                                    PriceColumnC = 56000,
                                    PriceColumnD = 69500,
                                    PriceColumnE = 63000,
                                    WeightOver = 0,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },
                                new RatesTable()
                                {
                                    Description = "500 gr tiếp theo",
                                    IsExtraColumn = true,
                                    MaxWeight = 0,
                                    MinWeight = 0,
                                    PriceColumnA = 2800,
                                    PriceColumnB = 5000,
                                    PriceColumnC = 6100,
                                    PriceColumnD = 9000,
                                    PriceColumnE = 8000,
                                    WeightOver = 500,
                                    IsDeleted =false,
                                    ModifiedByUserId = 1,
                                    ModifiedDate = DateTime.Now,
                                    MyOfficeId = 2
                                },

                            };

            pages.ForEach(c => context.RatesTables.Add(c));
            pages2.ForEach(c => context.RatesTables.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateMyOffices(TransportContext context)
        {
            var myOffices = new List<MyOffice>
                            {
                                new MyOffice
                                    {
                                        IsDeleted =false,
                                        Address = "3/7A Đồ Sơn, Phường 4, Q,Tân Bình, Tp.HCM",
                                        OfficeName = "Văn Phòng Tp.Hồ Chí Minh",
                                        PhoneNumber = "08. 6282.6888"
                                    },
                                new MyOffice
                                    {
                                        IsDeleted =false,
                                        Address = "Hà Nội",
                                        OfficeName = "Văn Phòng Hà Nội",
                                        PhoneNumber = "088888888"
                                    },
                            };

            myOffices.ForEach(c => context.MyOffices.Add(c));
            context.SaveChanges(); //save to database
        }

        private void CreateRegions(TransportContext context)
        {
            var regions = new List<Region>
                            {
                                new Region
                                    {
                                        IsDeleted = false,
                                        RegionName = "Vùng 1"
                                    },
                                new Region
                                {
                                    IsDeleted = false,
                                    RegionName = "Vùng 2"
                                },
                                new Region
                                {
                                    IsDeleted = false,
                                    RegionName = "Vùng 3"
                                },
                                new Region
                                {
                                    IsDeleted = false,
                                    RegionName = "Vùng 4"
                                },
                                new Region
                                {
                                    IsDeleted = false,
                                    RegionName = "Vùng 5"
                                },
                            };

            regions.ForEach(c => context.Regions.Add(c));
            context.SaveChanges(); //save to database
        }

        /// <summary>
        /// Random String
        /// </summary>
        /// <param name="size"></param>
        /// <param name="random"></param>
        /// <returns></returns>
        private static string RandomString(int size, Random random)
        {
            var builder = new System.Text.StringBuilder();
            for (int i = 0; i < size; i++)
            {
                //26 letters in the alfabet, ascii + 65 for the capital letters
                builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
            }
            return builder.ToString();
        }
    }

    public class RoleType
    {
        public const string Administrator = "Admin";
        public const string TruongBuuCuc = "T.Buu Cuc";
        public const string KhaiThac = "Khai Thac";
        public const string KTTruong = "KT Truong";
        public const string KTVien = "KT Vien";
        public const string NVGiaoNhan = "NV Giao Nhan";
    }

    public class PasswordHelper
    {
        public const int DEFAULT_SALT_SIZE = 16;

        public static string CreatePasswordSalt(int size)
        {
            string result = string.Empty;
            System.Security.Cryptography.RNGCryptoServiceProvider provider = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] bytes = new byte[size];
            provider.GetBytes(bytes);
            result = Convert.ToBase64String(bytes);
            return result;
        }

        public static string CreatePasswordHash(string password, string passwordSalt)
        {
            string result = string.Empty;
            string passwordAndSalt = string.Concat(password, passwordSalt);
            byte[] bytes = System.Text.UnicodeEncoding.Unicode.GetBytes(passwordAndSalt);
            System.Security.Cryptography.SHA1 provider = new System.Security.Cryptography.SHA1Managed();
            bytes = provider.ComputeHash(bytes);
            result = Convert.ToBase64String(bytes);
            return result;
        }
    }
}
